package cn.dengfanxin.gae.test.keyword;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetKeywordsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4892253265403637730L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//!so important sentence here
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		System.out.println("response encoding" + response.getCharacterEncoding());
		String xml = retrieveKeywords();
		System.out.println("result:\n" + xml);
		out.print(xml);
		out.flush();
		out.close();
	}

	@SuppressWarnings("unchecked")
	private String retrieveKeywords() {
		PersistenceManager pm = PMF.getInstance().getPersistenceManager();
		List<Keyword> keywords = new ArrayList<Keyword>();
		String xml = null;
		try{
			String query = "select from " + Keyword.class.getName();
			keywords = (List<Keyword>) pm.newQuery(query).execute();
			xml = XMLUtil.convertKeywordsToXML(keywords);
		}finally{
			pm.close();
		}
		return xml;
	}

}
